package com.ck.express.viewmodel

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ck.express.db.dao.FailedDeliveryRepository
import com.ck.express.db.entity.FailedDeliveryRequest
import kotlinx.coroutines.launch

class FailedDeliveryViewModel(private val repository: FailedDeliveryRepository) : ViewModel() {

    private val _failedDeliveries = MutableLiveData<List<FailedDeliveryRequest>>()
    val failedDeliveries: LiveData<List<FailedDeliveryRequest>> = _failedDeliveries

    fun loadFailedDeliveries() {
        viewModelScope.launch {
            val deliveries = repository.getAllFailedRequests()
            _failedDeliveries.postValue(deliveries)
        }
    }

    fun retryDelivery(request: FailedDeliveryRequest) {
        viewModelScope.launch {
            val updatedRequest = request.copy(retryCount = request.retryCount + 1)
            repository.updateFailedDelivery(updatedRequest)
            loadFailedDeliveries()
        }
    }
}